<template>
  <el-form :model="registerForm"
           ref="registerForm"
           :rules="rules"
           label-position="left"
           label-width="0px"
           @keydown.enter.native="register"
           class="login-container">
    <h3 class="login_title">注册</h3>
    <el-form-item prop="phoneNumber">
      <el-input type="tel" v-model="registerForm.phoneNumber" auto-complete="off" placeholder="手机号"></el-input>
    </el-form-item>
    <el-form-item prop="verCode">
      <el-input type="text" maxlength="6" v-model="registerForm.verCode" auto-complete="off" placeholder="验证码">
        <template slot="append">
          <keep-alive>
            <codeSend :phoneNumber="registerForm.phoneNumber"></codeSend>
          </keep-alive>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input type="text" v-model="registerForm.password" auto-complete="off" placeholder="密码" show-password>
      </el-input>
    </el-form-item>
    <el-form-item style="width: 100%">
      <el-button type="primary" style="width: 100%;background: #505458;border: none" @click.stop="register">注册
      </el-button>
    </el-form-item>
    <el-form-item>已有账号？
      <el-button type="text" style="color:#1a5b59;font-weight:bold" @click.stop="login">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import api from '@/apis/api';
import {registerRules} from "@/util/verify/rules";
import codeSend from '@/components/common/varCodeSend'
import {valiDate} from "../../util/verify/valiDate";

export default {
  name: 'register',
  data() {
    return {
      rules: registerRules,
      //表单
      registerForm: {
        phoneNumber: '',
        password: '',
        verCode: '',
      }
    }
  },
  components: {codeSend},
  methods: {
    async register() {
      const _this = this
      // 表单验证规则
      const valid = await valiDate(_this, "registerForm")
      if (!valid) return null
      const data = {
        phone: this.registerForm.phoneNumber,
        pwd: this.registerForm.password,
        smsCode: this.registerForm.verCode,
      }
      const result = await api.register(data)
      if (result.code === 200){
        this.$util.successMessage("注册成功")
        this.login()
      }else{
        this.$util.errorMessage(result.msg)
      }
    },
    //向父组件传参，切换组件状态
    login() {
      this.$emit("status", 'login')
    },
  },
}
</script>
